package com.smartparking.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
public class JwtUtil {

    @Value("${security.jwt.secret}")
    private String jwtSecret;

    @Value("${security.jwt.expiration-ms}")
    private long jwtExpirationMs;

    public String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpirationMs))
                .signWith(SignatureAlgorithm.HS256, jwtSecret)
                .compact();
    }

    public String getUsernameFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        // 方法1: 生成安全的随机密钥（推荐）
        SecretKey secretKey = io.jsonwebtoken.security.Keys.secretKeyFor(
                io.jsonwebtoken.SignatureAlgorithm.HS256
        );
        String base64Key = java.util.Base64.getEncoder().encodeToString(
                secretKey.getEncoded()
        );
        System.out.println("Generated secure key: " + base64Key);

        // 方法2: 使用固定长度的自定义密钥
        String customSecret = "your-secure-secret-key-with-at-least-32-characters";
        String customBase64Key = java.util.Base64.getEncoder().encodeToString(
                customSecret.getBytes(java.nio.charset.StandardCharsets.UTF_8)
        );
        System.out.println("Custom base64 key: " + customBase64Key);

        // 验证密钥长度
        byte[] decodedKey = java.util.Base64.getDecoder().decode(customBase64Key);
        System.out.println("Key length: " + decodedKey.length * 8 + " bits");
    }

}
